package com.xiaozhen.cmdb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaozhen.cmdb.dao.CmdbModelAttributeDao;
import com.xiaozhen.cmdb.dao.CmdbModelDao;
import com.xiaozhen.cmdb.service.CmdbModelService;
import com.xiaozhen.common.core.domain.cmdb.CmdbModel;
import com.xiaozhen.common.core.domain.cmdb.CmdbModelAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/8 17:21
 * @description:
 */
@Service
public class CmdbModelServiceImpl implements CmdbModelService {

    @Autowired
    private CmdbModelDao cmdbModelDao;
    @Autowired
    private CmdbModelAttributeDao cmdbModelAttributeDao;

    @Override
    public List<CmdbModel> selectCmdbModelList() {
        QueryWrapper<CmdbModel> queryWrapper = new QueryWrapper<>();
        List<CmdbModel> modelList = cmdbModelDao.selectList(queryWrapper);
        for (CmdbModel model : modelList) {
            QueryWrapper<CmdbModelAttribute> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("model_id", model.getModelId());
            List<CmdbModelAttribute> cmdbModelAttributes = cmdbModelAttributeDao.selectList(queryWrapper2);
            model.setModelAttributes(cmdbModelAttributes);
        }
        return modelList;
    }

    @Override
    public Integer insertCmdbModel(CmdbModel cmdbModel) {
        return cmdbModelDao.insert(cmdbModel);
    }

    @Override
    public Integer updateCmdbModel(CmdbModel cmdbModel) {
        return cmdbModelDao.updateById(cmdbModel);
    }

    @Override
    public Integer deleteModelById(Long modelId) {
        int count = cmdbModelDao.deleteById(modelId);
        if(count>0){
            QueryWrapper<CmdbModelAttribute> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("model_id",modelId);
            cmdbModelAttributeDao.delete(queryWrapper);
        }
        return count;
    }
}
